import React from "react";
import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import PageHeader from "@/components/PageHeader";
import { ControllerType } from "@/components/items-list/ItemsList";
import { BrowserRouter as Router,Link } from 'react-router-dom';//
import {Layout, Button, Col, Menu, Divider, Form, Input, Row, Table, ConfigProvider, Icon, Modal, Tree,AutoComplete} from "antd/lib";
import zhCN from 'antd/es/locale/zh_CN';
import Workflow from "@/services/workflow";
//import { createHashHistory } from 'history';
import {createBrowserHistory} from 'history'
import notification from "@/services/notification";
import {get} from "lodash";
import Enums from "@/services/enums";
import CreateTemplatesDialog from "@/components/contract/settings/TemplatesDialog";
import navigateTo from "@/components/ApplicationArea/navigateTo";
import {currentUser} from "@/services/auth";
import CheckDialog from "@/components/workflow/CheckDialog";
import routes from "@/services/routes";
import {WarningOutlined,SecurityScanTwoTone,DownOutlined} from "@ant-design/icons";
import Workflow_state from "@/services/workflow_state";
// import Templates from "@/services/templates";
const customHistory = createBrowserHistory();
//const HashHistory = createHashHistory();
//const history = useHistory();
const {Sider } = Layout;
const { confirm } = Modal;
class WorkFlowCheckList extends React.Component {
  state = {
    page: 1,
    pagesize: 10,
    total:10,
    loading: false,
    statename: '',
    data: [],
    gData: [],
    selectedKeys: '',
    selectedTitle: '',
    contractcode:'',
    contractname:'',
    seltype: "1",
    statedata:[],
  };
  componentWillMount() {
    this.loadData();
    let param={
      page: this.state.page,
      pagesize: this.state.pagesize,
      statename: this.state.statename,
      seltype: this.props.seltype,
      bill_enum: this.state.selectedKeys,
      userid:  currentUser.id,
      contractcode:this.state.contractcode,
      contractname:this.state.contractname,
    }
    this.fetch(param);
  }
  fetch = (params = {}) => {
    this.setState({ loading: true });
     Workflow.getchecklist(params).then(data => {
        this.setState({
            loading: false,
            data:data.data,
            page: params.page,
            pagesize: params.pagesize,
            total: data.total,
            selectedKeys: params.bill_enum,
            seltype: params.seltype,
        });
    });
  };
  handlesel = () => {
    let param={
      page: 1,
      pagesize: this.state.pagesize,
      statename: this.state.statename,
      seltype: this.state.seltype,
      bill_enum: this.state.selectedKeys,
      userid:  currentUser.id,
      contractcode:this.state.contractcode,
      contractname:this.state.contractname,
    }
    this.fetch(param);
  };
   handleTableChange = (pagination, filters, sorter) => {
    let field=sorter.field;
    let order=0;
    if(sorter.order==="descend"){
      order=1;
    }
    let param={
      field: field,
      order: order,
      page: pagination.current,
      pagesize: pagination.pageSize,
      statename: this.state.statename,
      seltype: this.state.seltype,
      bill_enum: this.state.selectedKeys,
      userid:  currentUser.id,
      contractcode:this.state.contractcode,
      contractname:this.state.contractname,
    }
    this.fetch(param);
  };
  handleUpdate = record => {
            let param={
                  page: this.state.page,
                  pagesize: this.state.pagesize,
                  statename: this.state.statename,
                  seltype: this.state.seltype,
                  bill_enum: this.state.selectedKeys,
                  userid:  currentUser.id,
                  contractcode:this.state.contractcode,
                  contractname:this.state.contractname,
            }
    CreateTemplatesDialog.showModal({templates: record})
    .onClose((result = {}) => {
        if (result.success) {
            this.fetch(param);
        }
      }).onDismiss(() => {
        navigateTo("templates", true);
      });
  };

  loadData=()=> {
    Enums.items("bill_enum").then(data => {
      const loop = (das, index) => {
        let items=[];
        das.forEach((item) => {
          item.icon= <SecurityScanTwoTone />;
          if (item.children) {
            item.children= loop(item.children, index+1);
          }
          items.push(item);
        });
        return items;
      };
      let datas=loop(data,0);
      this.setState({
        loading: false,
        gData: datas,
        selectedKeys: this.props.tablename,
        selectedTitle: '',
      });
    });

   let params={
      page: 1,
      pagesize: 200,
      name: "",
      workflowid:0,
    }
    Workflow_state.getlist(params).then(data => {
        this.setState({
          statedata:data.data,
      });
    });
  }
  onSelect = (selectedKeys, e) => {
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            statename: this.state.statename,
            seltype: this.state.seltype,
            bill_enum: selectedKeys[0],
            userid:  currentUser.id,
            contractcode:this.state.contractcode,
            contractname:this.state.contractname,
          }
          this.fetch(param);
};
  tabsClick = e => {
    let param={
      page: 1,
      pagesize: this.state.pagesize,
      statename: this.state.statename,
      seltype: e.key,
      bill_enum: this.state.selectedKeys,
      userid:  currentUser.id,
      contractcode:this.state.contractcode,
      contractname:this.state.contractname,
    }
    this.fetch(param);
  };
onDragEnter = info => {
    console.log(info);
  };
handleCheck = (record) => {
  if(!currentUser.isAudit){
    notification.error("没有权限.");
    return;
  }
    let item={
      bill: record.bill_enum,
      id: record.billid,
      message:"",
      status: record.billstatus,
      warnsealuser:"",
      billuserid: record.userid,
    }
    CheckDialog.showModal({bill_check: item})
    .onClose((result = {}) => {
        if (result.success) {
            let param={
              page: this.state.page,
              pagesize: this.state.pagesize,
              statename: this.state.statename,
              seltype: this.state.seltype,
              bill_enum: this.state.selectedKeys,
              userid:  currentUser.id,
              contractcode:this.state.contractcode,
              contractname:this.state.contractname,
            }
            this.fetch(param);
        }
      }).onDismiss(() => {
      });
  };
  render() {
    // const { currentPage } = this.state;
      const paginationProps = {
            showSizeChanger: true,
            // showQuickJumper: true,
            total: this.state.total, // 数据总数
            pageSize: parseInt(this.state.pagesize), // 每页条数
            current: parseInt(this.state.page), // 当前页码
            pageSizeOptions: ["10", "20", "30","100"],
            showTotal: ((total) => {
              return `共 ${total} 条`;
            }),
          };
    const listcolumns = [
      {
        title: '合同预编码',
        key: 'code',
        dataIndex: 'code',
        render: (text, record) => (
          <span>
           {(record.bill_enum ==="contractapply") && (
             <Router  history={customHistory}>
              <Link to={`/contract/apply/new/${record.billid}`}>{text}</Link>
             </Router>
           )}
           {(record.bill_enum ==="contracts") && (
             <Router  history={customHistory}>
              <Link to={`/contract/look/${record.billid}`}>{text}</Link>
             </Router>
           )}
           {(record.bill_enum ==="contractseal") && (
             <Router  history={customHistory}>
              <Link to={`/contract/seal/new/${record.billid}`}>{text}</Link>
             </Router>
           )}
           {(record.bill_enum ==="contractrecord") && (
             <Router  history={customHistory}>
              <Link to={`/contract/record/new/${record.billid}`}>{text}</Link>
             </Router>
           )}
           {(record.bill_enum ==="contractchange") && (
             <Router  history={customHistory}>
              <Link to={`/contract/change/new/${record.billid}`}>{text}</Link>
             </Router>
           )}
           {(record.bill_enum ==="contractprogress") && (
             <Router  history={customHistory}>
              <Link to={`/contract/progress/new/${record.billid}`}>{text}</Link>
             </Router>
           )}
           {(record.bill_enum ==="contractsettle") && (
             <Router  history={customHistory}>
              <Link to={`/contract/settle/new/${record.billid}`}>{text}</Link>
             </Router>
           )}
           {(record.bill_enum ==="contractstop") && (
             <Router  history={customHistory}>
              <Link to={`/contract/stop/new/${record.billid}`}>{text}</Link>
             </Router>
           )}
           {(record.bill_enum ==="contractfinish") && (
             <Router  history={customHistory}>
              <Link to={`/contract/finish/new/${record.billid}`}>{text}</Link>
             </Router>
           )}
          </span>
        ),
        sorter: (a, b) => a.code > b.code ? 1 : -1
      },
      // {
      //   title: '单据名称',
      //   dataIndex: 'tablename',
      //   key: 'tablename',
      //   sorter: (a, b) => a.tablename > b.tablename ? 1 : -1
      // },
      {
        title: '合同名称',
        dataIndex: 'name',
        key: 'name',
        sorter: (a, b) => a.name > b.name ? 1 : -1
      },
      {
        title: '合同起草日期',
        dataIndex: 'bill_dateformat',
        key: 'bill_dateformat',
        sorter: (a, b) => a.bill_dateformat > b.bill_dateformat ? 1 : -1
      },
      {
        title: '流程状态',
        dataIndex: 'statename',
        key: 'statename',
      },
      {
        title: '状态',
        key: 'status',
        dataIndex: 'status',
        render: (text, record) => (
          <span>
             {(this.state.seltype ==="1") &&(<p className="clickable">{this.state.seltype ==="1" ? "待审核":"驳回"}</p>)}
             {(this.state.seltype !=="1") &&(
             <p className="clickable" >{record.status ===2 ? "已审核":(record.status ===1 ? "已取消审核":"已驳回")}</p>)}
          </span>
        ),
      },
    ];
    return (
  <ConfigProvider locale={zhCN}>
      <div className="container">
        <PageHeader title={this.props.tablename==="contracts" ? "我审批的合同列表":"我的审批单据列表"}/>
      </div>
          {this.props.tablename ==="contracts" && (  
         <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
         <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同编码">
              <Input
                value={this.state.contractcode}
                onChange={e => {
                  localStorage.setItem("contractcode", e.target.value);
                  this.setState({contractcode: e.target.value});
                }}
                placeholder="合同编码"
              />
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同名称">
              <Input
                value={this.state.contractname}
                onChange={e => {
                  localStorage.setItem("contractname", e.target.value);
                  this.setState({contractname:e.target.value});}}
                placeholder="合同名称"
              />
            </Form.Item>
				  </Col>
        </Row>
          <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="流程状态">
            <AutoComplete
                dropdownClassName="certain-category-search-dropdown"
                dropdownMatchSelectWidth={400}
                style={{ width: 300 }}
                value={this.state.statename} 
                onChange={value => {this.setState({statename:value});}}
                placeholder="流程状态"
                filterOption={(inputValue, option) => 
                  option.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}>
                {(this.state.statedata || []).map(item => (
                  <AutoComplete.Option key={item.name} value={item.name}>{item.name}</AutoComplete.Option>
                ))}
              </AutoComplete>
						</Form.Item>
				  </Col>
          </Row>
          <Row>
				  <Col span={10}>
          <Button type="primary" onClick={() => this.handlesel()} >
            <i className="fa fa-search m-r-5" />
            查询
          </Button>
				  </Col>
          </Row>
         </Form>)}
      <Menu onClick={this.tabsClick} selectedKeys={this.state.seltype} mode="horizontal">
        <Menu.Item key = "1">{this.props.tablename==="contracts" ? "待我审核合同":"待我审核单据"}</Menu.Item>
        <Menu.Item key = "2">{this.props.tablename==="contracts" ? "我已审核合同":"我已经审核单据"}</Menu.Item>
        {/* <Menu.Item key = "3">{this.props.tablename==="contracts" ? "我已审核且完成审批流程未用印合同":"我已经审核且完成审批流程单据"}</Menu.Item>
        {this.props.tablename==="contracts" &&(<Menu.Item key = "4">{"我已审核且完成审批流程已用印合同"}</Menu.Item>)} */}
      </Menu>
          <div>
              <Table rowKey='id'
                     columns={listcolumns}
                     dataSource={this.state.data}
                     pagination={paginationProps}
                     loading={this.state.loading}
                     onChange={this.handleTableChange}
              />
         </div> 
  </ConfigProvider>    );
  }
}

routes.register(
  "Workflow.Billcheck",
  routeWithUserSession({
    path: "/workflow/billcheck",
    title: "待我审核的单据",
    render: pageProps => <WorkFlowCheckList {...pageProps} seltype="1" tablename=""/>,
  })
);
routes.register(
  "Workflow.Billcheck1",
  routeWithUserSession({
    path: "/workflow/billcheck/ok",
    title: "已审核的单据",
    render: pageProps => <WorkFlowCheckList {...pageProps} seltype="2"  tablename=""/>,
  })
);
routes.register(
  "Workflow.Billcheck2",
  routeWithUserSession({
    path: "/workflow/billcheck/contracts",
    title: "待我审核的合同",
    render: pageProps => <WorkFlowCheckList {...pageProps} seltype="1" tablename="contracts"/>,
  })
);
routes.register(
  "Workflow.Billcheck3",
  routeWithUserSession({
    path: "/workflow/billcheck/ok/contracts",
    title: "已审核的合同",
    render: pageProps => <WorkFlowCheckList {...pageProps} seltype="2" tablename="contracts"/>,
  })
);
